from django.shortcuts import render

from django.utils import timezone
from datetime import timedelta

from users.models import Usermodel
from life_style.models import Lifestyle,Editor_Recommend,LifestyleType


# Create your views here.
def index(request):
    user_head = ''
    user_info = request.session.get('user_info', None)
    if user_info:
        email = user_info['email']
        user = Usermodel.objects.filter(email=email).first()
        user_head = user.user_head

    # 综合 热门博客 --所有板块的综合热门  根据热度值 取top3
    time_range = [timezone.now() - timedelta(days=3), timezone.now()]
    hot_blog_list = Lifestyle.objects.filter(create_time__range=time_range).order_by('-hot')[:10]
    # 综合 热门博客 - end

    # 查询全站 最新博客
    new_blogs = Lifestyle.objects.filter().order_by('-create_time')[:4]

    # 查询编辑推荐数据  -- 博客
    rec_blogs = Editor_Recommend.objects.filter().order_by('-create_time')[:6]

    # 处理博客分类数量统计
    catogory_count = {}
    for catogory in LifestyleType.objects.all():
        catogory_count[catogory.__str__()] = Lifestyle.objects.filter(category=catogory).count()

    context = {}
    context['user_head'] = user_head
    context['hot_blog_list'] = hot_blog_list
    context['new_blogs'] = new_blogs
    # context['rec_blogs'] = rec_blogs[0]
    context['rec_blogs'] = rec_blogs
    context['shouye_active'] = "active"
    context['catogory_count'] = catogory_count
    return render(request, 'index.html', context)
